package com.chx.three.mama.utils;


import java.io.*;

/**
 * Created by Casio on 2015/2/6.
 */
public final class StreamUtil {
    //工具类不能够继承，不能够实例化。

    private StreamUtil(){}

    public static void close(Object stream){

        if (stream!=null){
            try{
                if (stream instanceof InputStream){
                    ((InputStream) stream).close();
                }else if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                }else if (stream instanceof Writer){
                    ((Writer) stream).close();
                }else if (stream instanceof Reader){
                    ((Reader) stream).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] ret = null;
        if (inputStream!=null){
            ByteArrayOutputStream bout=null;
            bout=new ByteArrayOutputStream();

            readStream(inputStream,bout);
            // bout.toByteArray() 在返回的时候，会将内部的数组
            // 复制一份，然后返回给ret,所以这个时候，两份拷贝
            // 必须进行释放，否则产生内存问题
            ret=bout.toByteArray();
            close(bout);
            bout=null;
        }
        return ret;
    }

    public static long readStream(InputStream in,OutputStream out) throws IOException {
        long ret =0;
        if (in!=null && out!=null){
            byte[] buf = new byte[128];
            int len;
            while (true){
                len=in.read(buf);
                if (len==-1){
                    break;
                }
                ret+=len;
                out.write(buf,0,len);
            }
            buf=null;
        }
        return ret;
    }

}
